package com.unnet.yjs.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 *  Email: love1208tt@foxmail.com
 *  Copyright (c) 2018. missbe
 *  @author lyg  19-5-21 下午9:43
 *
 **/

public class JavaBeanUtil {
    /**
     * 实体类转map
     * @param obj
     * @return
     *      
     */
    public static Map<String, Object> convertBeanToMap(Object obj) {
        if(obj == null){
            return null;
        }
        Map<String,Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors){
                String key = property.getName();
                if(!key.equals("class")){
                    Method getter = property.getReadMethod();
                    Object val = getter.invoke(obj);
                    if(null == val){
                        map.put(key, "");
                    }else{
                        map.put(key,val);
                    }
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return map;
    }
}
